<template>
  <div>
    <Header :title="'返回'" :subTitle="'搭配师列表'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-spin :spinning="spinning" size="large">
      <a-card :bordered="false">
        <a-anchor class="affix" ref="affix" :bounds="200" :style="{ top: fasId == 'add' ? '30px' : '300px' }">
          <a-anchor-link href="#components-basic" title="基本信息" />
          <a-anchor-link href="#components-static" title="案例" />
          <a-anchor-link href="#components" title="用户评价" />
        </a-anchor>
        <img :src="fasObj.photo" alt="" class="fas-photo" />
        <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 6 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 15 }, sm: { span: 17 } }">
          <a-row>
            <a-col :md="18" :sm="24">
              <div id="components-basic">
                <a-form-item label="是否用于小程序选择">
                  <a-switch v-decorator="['ifUseMiniappSw', { valuePropName: 'checked', initialValue: false, rules: [{ required: true }] }]" />
                </a-form-item>
                <a-form-item label="搭配师名称">
                  <a-input
                    v-decorator="['name', { rules: [{ required: true, max: 20, message: '请输入描述，不超过20个字符！' }] }]"
                    name="name"
                    placeholder="请输入"
                    :max-length="20"
                    autocomplete="off"
                  />
                </a-form-item>
                <a-form-item label="邮箱">
                  <a-input v-decorator="['email']" name="name" placeholder="请输入" autocomplete="off" />
                </a-form-item>
                <a-form-item label="工号">
                  <a-input v-decorator="['oaId']" name="name" placeholder="请输入" autocomplete="off" />
                </a-form-item>
                <a-form-item label="搭配师性别">
                  <a-radio-group name="radioGroup" v-decorator="['sex']">
                    <a-radio :value="1">男</a-radio>
                    <a-radio :value="2">女</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="擅长搭配">
                  <a-radio-group name="radioGroup" v-decorator="['expert']">
                    <a-radio value="30">通用</a-radio>
                    <a-radio value="10">男装</a-radio>
                    <a-radio value="20">女装</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="搭配师星座">
                  <a-select v-decorator="['constellation']" placeholder="请选择">
                    <a-select-option v-for="item in constellationList" :key="item" :value="item">{{ item }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="搭配师标签">
                  <template v-for="tag in fasObj.tagsList">
                    <a-tag :key="tag" :closable="true" @close="() => handleClose(tag)" class="">
                      {{ tag }}
                    </a-tag>
                  </template>
                  <a-input
                    v-if="!toggle"
                    ref="input"
                    type="text"
                    size="small"
                    :style="{ width: '78px' }"
                    :value="inputValue"
                    @change="handleInputChange"
                    @blur="handleInputConfirm"
                    @keyup.enter="handleInputConfirm"
                  />
                  <a-tag v-else style="background: #fff; borderstyle: dashed" @click="showInput"> <a-icon type="plus" /> New Tag </a-tag>
                </a-form-item>
                <a-form-item label="搭配师手机号">
                  <a-input v-decorator="['phone', { rules: [{ required: true, message: '请输入手机号！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
                </a-form-item>
                <a-form-item label="搭配师微信号">
                  <a-input v-decorator="['wechat', { rules: [{ required: true, message: '请输入微信号！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
                </a-form-item>
                <a-form-item label="搭配师描述">
                  <a-textarea v-decorator="['memo']" name="name" placeholder="请输入" autocomplete="off" rows="4" :max-length="200" />
                </a-form-item>
                <a-form-item label="用户说">
                  <a-textarea v-decorator="['evaluation']" name="name" placeholder="请输入" autocomplete="off" rows="4" :max-length="200" />
                </a-form-item>
                <a-form-item label="搭配师照片" required>
                  <JImageUpload :uploadParams="getUploadParams()" :isMultiple="false" :accept="'image/*'" :fileSize="3" @fileChange="e => fileChange(e, 'fas')" v-model="fasPhotos"></JImageUpload>
                  <div class="tips">请上传png/jpg格式的文件 图片大小需小于3M 请上传300x300的图片</div>
                </a-form-item>
                <a-form-item label="搭配师微信绑定" required>
                  <img :src="fasObj.ticket" alt="" style="width: 100px; height: 100px" />
                  <div style="line-height: 24px">为了推送搭配师模板消息,请扫描关注公众号<br />关注后,扫码的微信号将接收搭配师的模板消息提醒</div>
                </a-form-item>
                <a-form-item label="搭配师微信" required>
                  <JImageUpload
                    :uploadParams="getUploadParams()"
                    :isMultiple="false"
                    :accept="'image/*'"
                    :fileSize="0.2"
                    @fileChange="e => fileChange(e, 'wechat')"
                    v-model="wechatPhotos"
                  ></JImageUpload>
                  <div class="tips">请上传png/jpg格式的文件 图片大小需小于200K 请上传150x50的图片</div>
                </a-form-item>
                <a-form-item label="搭配师小程序码" required>
                  <img :src="fasObj.minQrcode" alt="" style="width: 100px; height: 100px" />
                  <div class="tips" style="margin-top: 8px; word-break: break-all">{{ fasObj.minQrcode }}</div>
                </a-form-item>
                <a-form-item label="搭配师签名" required>
                  <JImageUpload :uploadParams="getUploadParams()" :isMultiple="false" :accept="'image/*'" :fileSize="0.2" @fileChange="e => fileChange(e, 'sign')" v-model="signPhotos"></JImageUpload>
                  <div class="tips">请上传png/jpg格式的文件 图片大小需小于200K 请上传150x50的图片</div>
                </a-form-item>
                <a-form-item label="状态">
                  <a-radio-group name="radioGroup" v-decorator="['status']">
                    <a-radio :value="1">上架</a-radio>
                    <a-radio :value="0">下架</a-radio>
                  </a-radio-group>
                </a-form-item>
                <div class="btn-bottom">
                  <a-button htmlType="submit" type="primary" :loading="iconLoading">提交</a-button>
                  <a-button style="margin-left: 8px" @click="handleBack">关闭</a-button>
                </div>
              </div>
              <div style="margin-top: 48px" id="components-static">
                <h3>案例 <a-button type="primary" size="small" style="margin-left: 12px" icon="plus" @click="handleAddCase">新建</a-button></h3>
                <a-table :columns="caseColums" :rowKey="record => record.id" :data-source="caseList" :pagination="paginationPropsCase" @change="handleCaseTableChange" size="middle">
                  <span slot="photo" slot-scope="text">
                    <img :src="text" alt="" class="caseimg" />
                  </span>
                  <span slot="action" slot-scope="text, record, index">
                    <a @click="handleEdit(record)">
                      <a-icon type="edit" />
                    </a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确认删除该案例?" ok-text="Yes" cancel-text="No" @confirm="handleDelete(record, index)">
                      <a href="#"><a-icon type="delete" /></a>
                    </a-popconfirm>
                    <!-- <a @click="handleDelete(record, index)">
                      <a-icon type="delete" />
                    </a> -->
                    <a-divider type="vertical" />
                    <a-icon type="arrow-up" v-if="index == 0" :style="{ color: '#a9a9a9' }" />
                    <a @click="handleSort(index, 'up')" v-else>
                      <a-icon type="arrow-up" />
                    </a>
                    <a-divider type="vertical" />
                    <a-icon type="arrow-down" v-if="index + 1 == caseList.length" :style="{ color: '#a9a9a9' }" />
                    <a @click="handleSort(index, 'down')" v-else>
                      <a-icon type="arrow-down" />
                    </a>
                  </span>
                </a-table>
              </div>
              <div style="margin-top: 48px" id="components">
                <h3>评价</h3>
                <a-table :columns="evaluateColums" :rowKey="record => record.id" :data-source="evaluateList" :pagination="paginationProps" @change="handleTableChange" size="middle">
                  <span slot="createTime" slot-scope="text">{{ text }} </span>
                  <span slot="headUrl" slot-scope="text">
                    <img :src="text" alt="" class="headimg" />
                  </span>
                  <span slot="content" slot-scope="text">
                    <ellipsis :length="16" tooltip>{{ text }}</ellipsis>
                  </span>
                  <span slot="action" slot-scope="text, record">
                    <a-switch :checked="evaluateStatus(record.isShow)" @change="choose(record)" checked-children="开" un-checked-children="关" />
                  </span>
                </a-table>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </a-spin>
    <a-drawer title="编辑案例" placement="right" width="1000" :visible="visible" @close="onClose" :maskClosable="false" destroyOnClose>
      <a-form-model ref="rulesForm" :model="formCase" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 8 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }">
        <a-form-model-item label="案例名称" prop="name">
          <a-input :maxLength="10" v-model="formCase.name" placeholder="标题" />
          <div>注：请把字数控制在10字以内</div>
        </a-form-model-item>
        <a-form-model-item label="案例图" required>
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="false" :fileSize="0.6" :number="1" :accept="'image/*'" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
          <div>图片尺寸590*800，大小不超过600kb</div>
        </a-form-model-item>
        <a-form-model-item label="案例介绍" required>
          <j-editor v-model="formCase.description" />
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose"> 取消 </a-button>
        <a-button type="primary" @click="saveCase"> 保存 </a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import { Ellipsis } from '@/views/box/components'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import Header from '@/views/box/components/layouts/Header'
import JEditor from '@/components/qiniuUpload/JEditor'
import globalData from '@/assets/js/common'
import {
  fashionerDetail,
  fashionerCreate,
  fashionerGetCase,
  fashionerGetEvaluateList,
  fashionerUpdateEvaluate,
  fashionerCaseUpdateSort,
  fashionerCreateCase,
  fashionerDeleteCaseById
} from '@/api/box/setting'
import pick from 'lodash.pick'
let caseColums = [
  { title: '#', align: 'center', width: 50, customRender: (t, r, index) => index + 1 },
  { title: '名称', dataIndex: 'name', align: 'center' },
  { title: '图片', dataIndex: 'imgUrl', align: 'center', scopedSlots: { customRender: 'photo' } },
  { title: '操作', fixed: 'right', width: 150, align: 'center', scopedSlots: { customRender: 'action' } }
]
let evaluateColums = [
  { title: '#', align: 'center', width: 50, customRender: (t, r, index) => index + 1 },
  { title: '时间', dataIndex: 'createTime', align: 'center', width: 150 },
  { title: '昵称', dataIndex: 'nickName', align: 'center' },
  { title: '头像', dataIndex: 'headUrl', align: 'center', scopedSlots: { customRender: 'headUrl' } },
  { title: '评价', dataIndex: 'content', align: 'center', scopedSlots: { customRender: 'content' } },
  { title: '操作', fixed: 'right', width: 90, align: 'center', scopedSlots: { customRender: 'action' } }
]
export default {
  components: {
    JImageUpload,
    Header,
    Ellipsis,
    JEditor
  },
  data() {
    return {
      caseColums,
      evaluateColums,
      spinning: true,
      fasId: '',
      fasObj: {
        tagsList: []
      },
      form: this.$form.createForm(this),
      fasPhotos: [],
      signPhotos: [],
      wechatPhotos: [],
      constellationList: ['水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座'],
      inputValue: '',
      toggle: true,
      newFasPhotos: [],
      newSignPhotos: [],
      newWechatPhotos: [],
      caseList: [],
      evaluateList: [],
      paginationProps: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      paginationPropsCase: {
        pageNo: 1,
        pageSize: 5,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      visible: false,
      imgList: [],
      formCase: {
        name: '',
        img: {},
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      toolbar: ['styleselect forecolor| bullist numlist | underline strikethrough'],
      iconLoading: false
    }
  },
  computed: {
    evaluateStatus() {
      return text => {
        return text == 1
      }
    }
  },
  activated() {
    this.fasId = this.$route.params.id
    if (this.$route.params.id != 'add') {
      this.fetchDetail()
      this.fetchCase()
      this.fetchEvaluate()
    } else {
      this.spinning = false
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  methods: {
    headerBack() {
      this.$router.back()
    },
    fetchDetail() {
      let self = this
      let params = {
        requestData: {
          id: this.fasId
        }
      }
      fashionerDetail(params).then(res => {
        if (res.code == 0) {
          this.fasObj = res.data
          let data = res.data
          data.ifUseMiniappSw = data.ifUseMiniapp == 1
          data.tagsList = data.tags ? data.tags.split(',') : []
          this.fasPhotos = data.photo ? [data.photo] : []
          this.signPhotos = data.signImg ? [data.signImg] : []
          this.wechatPhotos = data.wechatUrl ? [data.wechatUrl] : []
          this.$nextTick(() => {
            setTimeout(() => {
              self.form.setFieldsValue(pick(data, 'name', 'email', 'oaId', 'ifUseMiniappSw', 'sex', 'expert', 'phone', 'wechat', 'memo', 'evaluation', 'status', 'constellation'))
            })
          })
        } else {
          this.$message.warning(res.msg)
        }
        this.spinning = false
      })
    },
    fetchCase() {
      const { pageNo, pageSize } = this.paginationPropsCase
      let params = {
        requestData: {
          id: this.fasId
        },
        page: {
          pageNo: pageNo,
          pageSize: pageSize
        }
      }
      fashionerGetCase(params).then(res => {
        if (res.code == 0) {
          this.caseList = res.data
          this.paginationPropsCase.total = res.page.count
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fetchEvaluate() {
      const { pageNo, pageSize } = this.paginationProps
      let params = {
        requestData: {
          id: this.fasId
        },
        page: {
          pageNo: pageNo,
          pageSize: pageSize
        }
      }
      fashionerGetEvaluateList(params).then(res => {
        if (res.code == 0) {
          this.evaluateList = res.data
          this.paginationProps.total = res.page.count
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleTableChange(pagination) {
      // console.log(pagination)
      this.paginationProps.pageNo = pagination.current
      this.fetchEvaluate()
    },
    handleCaseTableChange(pagination) {
      this.paginationPropsCase.pageNo = pagination.current
      this.fetchCase()
    },
    // 评价开关
    choose(record) {
      console.log(record)
      let params = {
        requestData: {
          isShow: record.isShow == 1 ? 0 : 1,
          id: record.id
        }
      }
      fashionerUpdateEvaluate(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功！')
          this.fetchEvaluate()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 案例编辑
    fileImageChange(list) {
      console.log('list', list)
      this.formCase.img = list.length ? list : ''
    },
    handleAddCase() {
      this.formCase = {
        name: '',
        img: [],
        description: ''
      }
      this.imgList = []
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.formCase = record
      this.imgList = [record.imgUrl]
    },
    handleDelete(record, index) {
      let params = {
        requestData: {
          id: record.id
        }
      }
      fashionerDeleteCaseById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('删除成功')
          this.caseList.splice(index, 1)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleSort(index, type) {
      let list = this.caseList
      if (type == 'up') {
        ;[list[index - 1], list[index]] = [list[index], list[index - 1]]
      }
      if (type == 'down') {
        ;[list[index + 1], list[index]] = [list[index], list[index + 1]]
      }
      this.$forceUpdate()
      this.caseList = this.caseList.map((e, index) => {
        return {
          ...e,
          priority: index + 1
        }
      })
      let params = {
        requestData: this.caseList
      }
      fashionerCaseUpdateSort(params).then(res => {
        if (res.code == 0) {
          this.$message.success('更换顺序成功！')
        } else {
          this.$message.warning(res.msg)
          this.fetchCase()
        }
      })
    },
    saveCase() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          if (this.formCase.img.length == 0) {
            this.$message.warning('请上传案例图！')
            return
          }
          if (!this.formCase.description) {
            this.$message.warning('案例介绍!')
            return
          }
          let params = {
            requestData: {
              ...this.formCase,
              imgUrl: this.formCase.img[0].url,
              fashionerId: this.fasId
            }
          }
          fashionerCreateCase(params).then(res => {
            if (res.code == 0) {
              this.$message.success('保存成功！')
              this.visible = false
              this.fetchCase()
            } else {
              this.$message.warning(res.msg)
            }
          })
        }
      })
    },
    onClose() {
      this.visible = false
      this.$refs.rulesForm.resetFields()
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileChange(list, type) {
      switch (type) {
        case 'fas':
          this.newFasPhotos = list
          break
        case 'sign':
          this.newSignPhotos = list
          break
        case 'wechat':
          this.newWechatPhotos = list
          break
      }
    },
    // 标签
    handleClose(removedTag) {
      const tags = this.fasObj.tagsList.filter(tag => tag !== removedTag)
      this.fasObj.tagsList = tags
    },
    showInput() {
      this.toggle = !this.toggle
      this.$nextTick(function () {
        this.$refs.input.focus()
      })
    },
    handleInputChange(e) {
      this.inputValue = e.target.value
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      let tags = this.fasObj.tagsList
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue]
      }
      // console.log(tags)
      this.fasObj.tagsList = tags
      Object.assign(this, {
        tags,
        toggle: true,
        inputValue: ''
      })
      console.log(this)
    },
    handleSubmit(e) {
      e.preventDefault()
      this.iconLoading = true
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.newFasPhotos.length == 0) {
            this.$message.warning('请上传搭配师照片')
            this.iconLoading = false
            return
          }
          if (this.newWechatPhotos.length == 0) {
            this.$message.warning('请上传搭配师微信')
            this.iconLoading = false
            return
          }
          if (this.newSignPhotos.length == 0) {
            this.$message.warning('请上传搭配师签名')
            this.iconLoading = false
            return
          }
          let formValues = {}
          Object.assign(formValues, values)
          formValues = {
            ...formValues,
            tags: this.fasObj.tagsList.join(','),
            photo: this.newFasPhotos.length > 0 ? this.newFasPhotos[0].url : '',
            signImg: this.newSignPhotos.length > 0 ? this.newSignPhotos[0].url : '',
            wechatUrl: this.newWechatPhotos.length > 0 ? this.newWechatPhotos[0].url : '',
            ifUseMiniapp: formValues.ifUseMiniappSw ? 1 : 0,
            isSales: 0
          }
          if (this.fasId != 'add') formValues.id = this.fasObj.id

          delete formValues.ifUseMiniappSw
          console.log(formValues)
          this.submitCreate(formValues)
        } else {
          this.iconLoading = false
        }
      })
    },
    submitCreate(d) {
      let params = {
        requestData: d
      }
      fashionerCreate(params).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功！')
          this.handleBack()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleBack() {
      this.$router.back()
    }
  }
}
</script>
<style lang="less" scoped>
.tips {
  line-height: 16px;
}
.fas-photo {
  width: 250px;
  height: 250px;
  display: block;
  position: absolute;
  right: 50px;
  z-index: 2;
  object-fit: cover;
}
.tag {
  position: relative;
  margin-right: 16px;

  /deep/ .ant-tag {
    font-size: 16px;
  }
  .del-tag {
    position: absolute;
    right: 0;
    top: -10px;
    z-index: 2;
    font-size: 20px;
  }
}
.btn-bottom {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
.caseimg {
  width: 100px;
  height: 100px;
  object-fit: scale-down;
}
.headimg {
  width: 60px;
  height: 60px;
  object-fit: scale-down;
}
.tinymce-editor {
  /deep/.tox-tinymce {
    height: 600px !important;
  }
}
/deep/.ant-card-body {
  position: relative;
}
/deep/.ant-affix {
  top: 65px !important;
}
/deep/.ant-anchor {
  font-size: 16px;
}
/deep/.ant-anchor-link {
  line-height: 2;
}
.affix {
  right: 50px;
  z-index: 2;
  width: 250px;
  position: absolute;
}
</style>

